<template>
  <div class="flex wh-full">
    <!--表单区域-->
    <Left
      ref="leftRef"
      :is-generating="isGenerating"
      @submit="submit"
      @direct-generate="directGenerate"
    />
    <!--右边生成思维导图区域-->
    <Right
      ref="rightRef"
      :generatedContent="generatedContent"
      :isEnd="isEnd"
      :isGenerating="isGenerating"
      :isStart="isStart"
    />
    <History @mapListClickHanler="mapListClickHanler" @removeJob="removeJob" ref="historyRef" />
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, reactive, nextTick, watch } from "vue";
import Left from "./components/Left.vue";
import Right from "./components/Right.vue";
import History from "./components/History.vue";
import { AiMindMapApi } from "@/api/ai/mindmap";
import { MindMapContentExample } from "@/utils/ai/constants";
import { useMessage } from "@/hooks/web/useMessage";
defineOptions({
  name: "AiMindMap",
});
const ctrl = ref(); // 请求控制
const isGenerating = ref(false); // 是否正在生成思维导图
const isStart = ref(false); // 开始生成，用来清空思维导图
const isEnd = ref(true); // 用来判断结束的时候渲染思维导图
const message = useMessage(); // 消息提示

const generatedContent = ref(""); // 生成思维导图结果

const leftRef = ref(); // 左边组件
const rightRef = ref(); // 右边组件
const historyRef = ref();
const currentField = reactive({ id: "", prompt: "", generatedContent: "" });
/** 使用已有内容直接生成 **/
const directGenerate = async (existPrompt) => {
  if (!existPrompt) {
    message.error("请输入内容");
    return
  }
  currentField.generatedContent = existPrompt;
  getPrompt();
  isEnd.value = false; // 先设置为 false 再设置为 true，让子组建的 watch 能够监听到
  await AiMindMapApi.regenerateMapPage(currentField);
  historyRef?.value.refreshList();
  generatedContent.value = existPrompt;
  isEnd.value = true;
};

/** 停止 stream 生成 */
const stopStream = () => {
  isGenerating.value = false;
  isStart.value = false;
  ctrl.value?.abort();
};

const getPrompt = (params) => {
  currentField.prompt = leftRef.value?.getPrompt();
};
/** 提交生成 */
const submit = (data) => {
  getPrompt();
  isGenerating.value = true;
  isStart.value = true;
  isEnd.value = false;
  ctrl.value = new AbortController(); // 请求控制赋值
  generatedContent.value = ""; // 清空生成数据
  AiMindMapApi.generateMindMap({
    data,
    onMessage: async (res) => {
      const { code, data, msg } = JSON.parse(res.data);
      if (code !== 0) {
        message.alert(`生成思维导图异常! ${msg}`);
        stopStream();
        return;
      }
      generatedContent.value = generatedContent.value + data;
      await nextTick();
      rightRef.value?.scrollBottom();
    },
    onClose() {
      isEnd.value = true;
      leftRef.value?.setGeneratedContent(generatedContent.value);
      historyRef?.value.refreshList();
      stopStream();
    },
    onError(err) {
      console.error("生成思维导图失败", err);
      stopStream();
    },
    ctrl: ctrl.value,
  });
};

const mapListClickHanler = (item, i) => {
  console.log("item :>> ", item);
  currentField.id = item.id;
  generatedContent.value = item.generatedContent;
  leftRef.value?.setGeneratedContent(generatedContent.value);
  leftRef.value?.setPrompt(item.prompt);
};
const removeJob = (item) => {
  if (item.id === currentField.id) {
    resetMap();
  }
};
const resetMap = (params) => {
  leftRef.value?.setPrompt("");
  generatedContent.value = "";
  leftRef.value?.setGeneratedContent("");
};
/** 初始化 */
onMounted(() => {
  // generatedContent.value = MindMapContentExample;
  // generatedContent.value = "# 暂无数据";
});
</script>
